package com.handyshop.mall.auth.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.handyshop.mall.auth.constants.BaseOauthConstants;
import com.handyshop.mall.auth.vo.AuthUserVo;
import com.handyshop.mall.dubbo.user.api.ISysUserDubboService;
import com.handyshop.mall.dubbo.user.dto.user.UserVo;
import com.handyshop.mall.dubbo.user.entity.SysMenu;
import com.handyshop.mall.dubbo.user.entity.SysRole;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author handy
 * @date 2020/11/12 15:15
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @DubboReference
    private ISysUserDubboService sysUserDubboService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVo userVo = sysUserDubboService.findByName(username);
        if (userVo == null) {
            throw new UsernameNotFoundException("用户或者密码错误!");
        }
        if (userVo.getLockFlag()) {
            throw new LockedException("该帐号已被冻结");
        }

        // 线上环境应该通过用户名查询数据库获取加密后的密码
        // String password = passwordEncoder.encode("123456");

        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        Set<String> authoritiesSet = new HashSet<>();
        // 获取角色
        if (CollUtil.isNotEmpty(userVo.getSysRoles())) {
            for (SysRole sysRole : userVo.getSysRoles()) {
                authoritiesSet.add(BaseOauthConstants.ROLE + sysRole.getName());
            }
        }
        // 获取资源
        if (CollUtil.isNotEmpty(userVo.getSysMenus())) {
            for (SysMenu sysMenu : userVo.getSysMenus()) {
                if (StrUtil.isNotBlank(sysMenu.getPermission())) {
                    authoritiesSet.add(sysMenu.getPermission());
                }
            }
        }
        for (String str : authoritiesSet) {
            authorities.add(new SimpleGrantedAuthority(str));
        }
        return new AuthUserVo(userVo.getId(), username, userVo.getPassword(), authorities);
    }

}